const express = require('express');

const co = require('co');

const router = express.Router();

const config = require('../../config/config');

const dataManager = require('../../db/data_manager');

const ipUtils = require('../../utils/ip_utils');

const resultUtils = require('../../utils/result_utils');

const qiniuUtils = require('../../utils/qiniu_utils');

/**
 * @apiDefine List_200
 * @apiSuccess (Reponse 200) {Number} code 0000为成功，-1位异常
 * @apiSuccess (Reponse 200) {Object} result 数组对象
 * @apiSuccessExample {json} Response 200 Example
 *    HTTP/1.1 200 OK
 *    {
 *      "code": "0000",
 *      "ret": 0,
 *      "desc": "success",
 *      "result": {
 *         "data": [],
 *         "page": {
 *           "size": 5,
 *           "page": 1,
 *           "totalElements": 0,
 *           "totalPages": 0
 *          }
 *       }
 *    }
 */

/**
 * 查询用户信息列表
 * @api {get} admin/list 查询用户信息列表
 * @apiName list
 * @apiDescription 查询用户信息列表
 * @apiGroup user
 * @apiVersion 1.0.0
 * @apiParam {String} page 页数
 * @apiParam {String} size 大小
 * @apiParamExample  {type} Request-Example:
 *    {
 *      "user_code": "001"
 *    }
 * @apiSampleRequest /api/admin/list
 * @apiUse List_200
 */

router.get('/list', (req, res) => {
  co(function* () {
    const page = req.query.page ? parseInt(req.query.page, 10) : 1;
    const size = req.query.size ? parseInt(req.query.size, 10) : Number.MAX_SAFE_INTEGER;
    const result = yield dataManager.AdminHelp.findAll(page, size);
    res.send(
      resultUtils.createSuccessListResponse(result.rows, {
        size,
        page,
        totalElements: result.count,
        totalPages: parseInt(`${(result.count - 1) / size + 1}`, 10),
      })
    );
  }).catch(error => {
    console.log(error);
    res.send(resultUtils.createErrorResponse(resultUtils.ErrorCode.ERROR_CODE_SYSTEM_ERROR));
  });
});

router.get('/findById', (req, res) => {
  co(function* () {
    const id = req.query.id;
    const result = yield dataManager.AdminHelp.findById(id);
    res.send(resultUtils.createSuccessResponse(result));
  }).catch(error => {
    console.log(error);
    res.send(resultUtils.createErrorResponse(resultUtils.ErrorCode.ERROR_CODE_SYSTEM_ERROR));
  });
});

router.post('/login', (req, res) => {
  co(function* () {
    const params = req.body;
    const admin = yield dataManager.AdminHelp.findByUserNameAndPwd(params.username, params.password);
    if (!admin) {
      res.send(resultUtils.createErrorResponse(resultUtils.ErrorCode.ERROR_CODE_USER_NOT_FOUND));
      return;
    }
    req.session.user = admin;
    admin.last_ip = ipUtils.getClientIp(req);
    dataManager.AdminHelp.update(admin);

    /* 登录时下发用户信息以及七牛配置 */
    res.send(
      resultUtils.createSuccessResponse({
        admin,
        qiniu: { baseUrl: config.qiniu.baseUrl, token: qiniuUtils.getUploadToken() },
      })
    );
  }).catch(error => {
    console.log(error);
    res.send(resultUtils.createErrorResponse(resultUtils.ErrorCode.ERROR_CODE_SYSTEM_ERROR));
  });
});

router.post('/create', (req, res) => {
  co(function* () {
    const params = req.body;
    if (!params || !params.user_name || !params.pass_word || !params.name) {
      res.send(resultUtils.createErrorResponse(resultUtils.ErrorCode.ERROR_CODE_PARAMS_ERROR));
      return;
    }
    const result = yield dataManager.AdminHelp.create(params);
    res.send(resultUtils.createSuccessResponse(result));
  }).catch(error => {
    console.log(error);
    res.send(resultUtils.createErrorResponse(resultUtils.ErrorCode.ERROR_CREATE_FAIL));
  });
});

router.post('/update', (req, res) => {
  co(function* () {
    const params = req.body;
    if (!params || !params.id || !params.user_name || !params.pass_word) {
      res.send(resultUtils.createErrorResponse(resultUtils.ErrorCode.ERROR_CODE_PARAMS_ERROR));
      return;
    }
    const result = yield dataManager.AdminHelp.update(params);
    res.send(resultUtils.createSuccessResponse(result));
  }).catch(error => {
    console.log(error);
    res.send(resultUtils.createErrorResponse(resultUtils.ErrorCode.ERROR_CODE_SYSTEM_ERROR));
  });
});

router.post('/delete', (req, res) => {
  co(function* () {
    const params = req.body;
    if (!params || !params.id) {
      res.send(resultUtils.createErrorResponse(resultUtils.ErrorCode.ERROR_CODE_PARAMS_ERROR));
      return;
    }
    const result = yield dataManager.AdminHelp.delete(params);
    res.send(resultUtils.createSuccessResponse(result));
  }).catch(error => {
    console.log(error);
    res.send(resultUtils.createErrorResponse(resultUtils.ErrorCode.ERROR_CODE_SYSTEM_ERROR));
  });
});
module.exports = router;
